package com.fzu.geometa.metadata.util;

import com.fzu.geometa.rpc.ValidateRequest;
import com.fzu.geometa.rpc.ValidateResponse;
import com.fzu.geometa.rpc.ValidateServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ValidateClient {
    private static final Logger logger = Logger.getLogger(ValidateClient.class.getName());

    private final ManagedChannel channel;
    private final ValidateServiceGrpc.ValidateServiceBlockingStub blockingStub;

    public ValidateClient(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build());
    }

    private ValidateClient(ManagedChannel channel) {
        this.channel = channel;
        blockingStub = ValidateServiceGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public boolean validate(String standard, String group, String data) {
        ValidateRequest request = ValidateRequest.newBuilder()
                .setStandard(standard)
                .setGroup(group)
                .setData(data)
                .build();
        logger.info("Sending request to server: " + request);
        ValidateResponse response;
        try {
            response = blockingStub.validate(request);
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
            return false;
        }
        logger.info("Received response from server: " + response.getPassed());
        return response.getPassed();
    }
}
